package com.lzy.chat.c_service;

import com.lzy.chat.a_entity.User;
import com.lzy.chat.b_mapper.UserMapper;
import com.lzy.chat.c_service.Exception.Exceptions;
import com.lzy.chat.c_service.Exception.ServiceException;
import com.lzy.chat.e_util.GetCode;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.mail.internet.AddressException;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper user) {
        this.userMapper = user;
    }


    private JavaMailSender javaMailSender;

    @Autowired
    public void setJavaMailSender(JavaMailSender javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Override
    public Map<String, Object> verify(String email, String phone, Integer type) {
        //注册验证 type=0
        //登录验证、更新密码 type=1
        Integer id;
        if (type == 0) {
            if (email != null) {
                id = userMapper.getUserByEmail(email);
                if (id != null) throw new ServiceException(Exceptions.EmailException, "邮箱已被注册");
            } else {
                id = userMapper.getUserByPhone(phone);
                if (id != null) throw new ServiceException(Exceptions.PhoneException, "手机号已被注册");
            }
        } else {
            if (email != null) {
                id = userMapper.getUserByEmail(email);
                if (id == null) throw new ServiceException(Exceptions.SendEmailException, "邮箱未注册");
            } else {
                id = userMapper.getUserByPhone(phone);
                if (id == null) throw new ServiceException(Exceptions.SendPhoneException, "手机号未注册");
            }
        }
        String code = GetCode.getVerifyCode();
        try {
            if (email != null)
                javaMailSender.send(GetCode.sendMail(email, code));
            else {
                GetCode.sendMessage(phone, code);
            }
        } catch (MailSendException e) {
            throw new ServiceException(Exceptions.SendCodeException);
        } catch (AddressException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("id", id);
        return map;
    }

    @Override
    public Integer register(User user) {
        String password = user.getPassword();
        String salt = UUID.randomUUID().toString().toUpperCase();
        user.setSalt(salt);
        String newPassword = getSHA256Password(password, salt);
        user.setPassword(newPassword);
        user.setBirth(new Date());
        user.setEmail(user.getEmail());
        user.setPhone(user.getPhone());
        Integer res = userMapper.insertUser(user);
        if (res != 1) throw new ServiceException(Exceptions.UserInsertException);
//        System.out.println(user.getId());
        return user.getId();//返回id值
    }

    @Override
    public List<User> getUsersByIdOrName(String keyword) {
        return userMapper.getUserByName(keyword);
    }


    @Override
    public void updateUserPassword(String newPassword, String oldPassword, User user) {
        String salt = user.getSalt();
        String oldSHAPassword = user.getPassword();
        String inputOldSHAPassword = getSHA256Password(oldPassword, salt);
        if (!oldSHAPassword.equals(inputOldSHAPassword))
            throw new ServiceException(Exceptions.UserPasswordNotMatchException);
        String newSHAPassword = getSHA256Password(newPassword, salt);
        Integer res = userMapper.updateUserPassword(user.getId(), newSHAPassword);
        if (res != 1) throw new ServiceException(Exceptions.UserUpdateException, "密码修改失败");
    }

    @Override
    public void findUserPassword(String newPassword, Integer id) {
        User user = getInfoById(id);
        String salt = user.getSalt();
        String newSHAPassword = getSHA256Password(newPassword, salt);
        Integer res = userMapper.updateUserPassword(id, newSHAPassword);
        if (res != 1) throw new ServiceException(Exceptions.UserUpdateException, "密码修改失败");
    }

    @Override
    public void updateUserInfo(User user) {
        Integer res = userMapper.updateUser(user);
        if (res != 1) throw new ServiceException(Exceptions.UserUpdateException, "用户信息更新失败");
    }

    @Override
    public User getInfoById(Integer id) {
        User user = userMapper.getUserById(id);
        if (user == null) throw new ServiceException(Exceptions.UserNotFoundException, "未找到此用户->id:" + id);
        return user;
    }

    //算法加密
    static String getSHA256Password(String password, String salt) {
        return new SimpleHash("SHA-256", password, salt, 20).toString();
    }

}

